from urllib.request import urlopen,Request
from urllib import parse
from urllib import request
import json

# # 请求地址 get
# url =  'https://httpbin.org/get'
# # 发起请求
# response = request.urlopen(url)
# # 解析响应
# if response.status == 200:
# 	response_bytes = response.read()
# 	response_text = response_bytes.decode('utf-8')
# 	response_json = json.loads(response_text)
# 	print(response_json)



# # 请求地址 get
# url =  'https://httpbin.org/get'
# # 添加请求头
# header = {
# 	'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36',
# }
# response = Request(url,headers=header)
# response = urlopen(response)
# if response.status == 200:
# 		response_bytes = response.read()
# 		response_text = response_bytes.decode('utf-8')
# 		response_json = json.loads(response_text)
# 		print(response_json['headers'])

# # 请求地址 post
# url =  'https://httpbin.org/post'
# header = {
# 	'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36',
# }
# data = {
# 	'name': '张三',
# 	'age': 18
# }
# data_encode = parse.urlencode(data).encode('utf-8')
# request1 = Request(url, headers=header, data=data_encode , method='POST')
# response = urlopen(request1)
# print(response.read().decode('utf-8'))


# 请求地址 post
url =  'https://httpbin.org/post'
header = {
	'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36',
	'content-type' : 'application/json'
}
data = {
	'name': '张三',
	'age': 18
}
data_encode = json.dumps(data).encode('utf-8')
request2 = Request(url, headers=header, data=data_encode , method='POST')
response = urlopen(request2)
if response.status == 200:
	print(response.read().json.loads())